<template>
  <div>
    <el-form label-width="100px" :model="form" ref="form" :rules="rulesForm">
      <el-form-item :label="$t('订单编号')">
        <div style="line-height: 32px">
          {{ rows.loanRecordId }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('待还本金')">
        <div style="line-height: 32px">
          {{ rows.residuePrincipalFine }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('待还罚息')">
        <div style="line-height: 32px">
          {{ rows.residueOverdueFine }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('剩余应还金额')">
        <div style="line-height: 32px">
          {{ rows.notRefundAmount }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('减免时间')" prop="actualRefundTimestamp">
        <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.actualRefundTimestamp"
            type="datetime"
            :pickerOptions="pickerOptions"
            :placeholder="$t('选择日期时间')">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('减免类型')" prop="cause1">
        <el-select v-model="form.cause1" @change="changeType">
          <el-option v-for="item in remissionTypeList" :label="item.value" :value="item.key"
                     :key="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('减免原因')" prop="cause2" v-if="!isRequired" :required="!isRequired" :rules="!isRequired  ? [
          {required: true, message: this.$t('不能为空'),},
        ] : []">
        <el-select v-model="form.cause2">
          <el-option v-for="item in remissionCauseList" :label="item.value" :value="item.key"
                     :key="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('减免金额')" prop="remissionAmount">
        <el-input v-model="form.remissionAmount" oninput="value = value.replace(/[^\d.]/g, '')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('上传凭证')">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            ref="upload"
            action="#"
            accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
            :http-request="uploadChange">
          <img v-if="form.certificate" :src="form.certificate" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item :label="$t('备注')" prop="remark" :required="isRequired" :rules="isRequired  ? [
          {required: true, message: this.$t('不能为空'),},
        ] : []">
        <el-input type="textarea" :rows="4" v-model="form.remark"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {overdueFineDerate,uploadOverdueCertificate,remissionCause} from '@/api/finance'
export default {
  props: ['rows'],
  data() {
    return {
      form: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      remissionTypeList: [],
      remissionAllList: [],
      remissionCauseList: [],
      rulesForm: {
        actualRefundTimestamp: [
          {required: true, message: this.$t('不能为空'),},
        ],
        remissionType: [
          {required: true, message: this.$t('不能为空'),},
        ],
        cause1: [
          {required: true, message: this.$t('不能为空'),},
        ],
        cause2: [
          {required: true, message: this.$t('不能为空'),},
        ],
        remissionAmount: [
          {required: true, message: this.$t('不能为空'),},
        ],
      },
      isRequired: false,
    }
  },
  mounted() {
    this.getRemissionCause()
  },
  methods: {
    submitForm() {
      return new Promise((resolve) => {
        this.$refs.form.validate(async v => {
          if (v) {
            if (parseInt(this.form.remissionAmount)  > this.rows.notRefundAmount ) return this.$message.error(this.$t('减免金额不能超过当前剩余应还金额'))
            this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
              type: "warning",
            }).then(async () => {
              this.$emit('loading', true)
              const res = await overdueFineDerate(
                  {
                    ...this.form,
                    loanRecordId: this.rows.loanRecordId
                  }
              )
              if (res.code === 1) {
                resolve(res.code)
                this.$emit('loading', false)
                this.$refs.upload.clearFiles()
                this.$message.success(this.$t('操作成功'))
              } else {
                this.$emit('loading', false)
              }
            }).catch(()=>{});

          }
        })
      })
    },
    async uploadChange(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      formData.append('loanRecordId', this.rows.loanRecordId)
      const res = await uploadOverdueCertificate(formData)
      if (res.code === 1) {
        this.$set(this.form, 'certificate', res.data)
      }
    },
    async getRemissionCause() {
      const res = await remissionCause()
      if (res.code === 1) {
        this.remissionAllList = [...res.data]
        this.remissionTypeList = [...res.data].filter(i => i.code === 0)
      }
    },
    changeType(key) {
      const selectType = this.remissionAllList.filter(i => i.key === key)
      const list = this.remissionAllList.filter(i => {
        return i.type === selectType[0].type && i.code !== 0
      })
      this.remissionCauseList = list
      if (selectType[0].isRemark && selectType[0].isRemark === 1) {
        // 类型其他 必填备注 去除原因校验
        this.isRequired = true
      } else {
        this.isRequired = false
      }
      if (this.form.cause2) this.form.cause2 = null
    },
    clearForm() {
      this.$refs.form.resetFields()
      this.form = {}
      this.isRequired = false
    }
  }
}
</script>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
